#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Linux权限维持清理验证器
用于验证权限维持机制的清理和恢复功能
"""

import os
import sys
import json
import time
import subprocess
import shutil
import hashlib
from datetime import datetime
from pathlib import Path

class PersistenceCleanupVerifier:
    def __init__(self):
        self.session_id = datetime.now().strftime("%Y%m%d_%H%M%S")
        self.backup_dir = f"/tmp/cleanup_backup_{self.session_id}"
        self.results = {
            'session_id': self.session_id,
            'timestamp': datetime.now().isoformat(),
            'cleanup_tests': [],
            'recovery_tests': [],
            'overall_status': 'unknown'
        }
        
        # 创建备份目录
        os.makedirs(self.backup_dir, exist_ok=True)
        
        # 测试配置
        self.test_configs = {
            'ssh_key': {
                'files': [
                    '~/.ssh/.test_backdoor_key',
                    '~/.ssh/.test_backdoor_key.pub'
                ],
                'auth_keys_entry': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC... test-backdoor-key',
                'description': 'SSH密钥后门清理测试'
            },
            'systemd_service': {
                'service_name': 'test-backdoor.service',
                'service_file': '/etc/systemd/system/test-backdoor.service',
                'exec_script': '/usr/local/bin/test-backdoor',
                'description': 'Systemd服务后门清理测试'
            },
            'cron_job': {
                'cron_entry': '*/5 * * * * /usr/bin/test-backdoor-script >/dev/null 2>&1',
                'script_file': '/usr/bin/test-backdoor-script',
                'description': 'Cron定时任务后门清理测试'
            },
            'env_variable': {
                'script_file': '/etc/profile.d/.test-backdoor.sh',
                'env_var': 'TEST_BACKDOOR_TRIGGER',
                'description': '环境变量后门清理测试'
            },
            'file_trigger': {
                'trigger_file': '/tmp/.test_trigger',
                'response_file': '/var/log/.test_response.log',
                'monitor_script': '/usr/local/bin/test-file-monitor',
                'description': '文件触发后门清理测试'
            },
            'shell_alias': {
                'bashrc_file': '~/.bashrc',
                'alias_entry': "alias ls='ls --color=auto; /tmp/.test_alias_trigger'",
                'description': 'Shell别名后门清理测试'
            }
        }
    
    def log_info(self, message):
        """记录信息日志"""
        print(f"[INFO] {message}")
    
    def log_success(self, message):
        """记录成功日志"""
        print(f"[SUCCESS] {message}")
    
    def log_warning(self, message):
        """记录警告日志"""
        print(f"[WARNING] {message}")
    
    def log_error(self, message):
        """记录错误日志"""
        print(f"[ERROR] {message}")
    
    def run_command(self, command, shell=True):
        """执行系统命令"""
        try:
            result = subprocess.run(
                command,
                shell=shell,
                capture_output=True,
                text=True,
                timeout=30
            )
            return result.returncode == 0, result.stdout, result.stderr
        except subprocess.TimeoutExpired:
            return False, "", "Command timeout"
        except Exception as e:
            return False, "", str(e)
    
    def backup_file(self, file_path):
        """备份文件"""
        expanded_path = os.path.expanduser(file_path)
        if os.path.exists(expanded_path):
            backup_name = os.path.basename(expanded_path)
            backup_path = os.path.join(self.backup_dir, backup_name)
            shutil.copy2(expanded_path, backup_path)
            self.log_info(f"已备份文件: {expanded_path} -> {backup_path}")
            return backup_path
        return None
    
    def restore_file(self, original_path, backup_path):
        """恢复文件"""
        if os.path.exists(backup_path):
            expanded_path = os.path.expanduser(original_path)
            shutil.copy2(backup_path, expanded_path)
            self.log_info(f"已恢复文件: {backup_path} -> {expanded_path}")
            return True
        return False
    
    def deploy_test_ssh_key_backdoor(self):
        """部署测试SSH密钥后门"""
        self.log_info("部署测试SSH密钥后门...")
        
        config = self.test_configs['ssh_key']
        ssh_dir = os.path.expanduser('~/.ssh')
        
        # 确保.ssh目录存在
        os.makedirs(ssh_dir, exist_ok=True)
        os.chmod(ssh_dir, 0o700)
        
        # 备份authorized_keys
        auth_keys_path = os.path.join(ssh_dir, 'authorized_keys')
        self.backup_file(auth_keys_path)
        
        # 生成测试密钥
        key_path = os.path.expanduser(config['files'][0])
        success, _, _ = self.run_command(f'ssh-keygen -t rsa -b 2048 -f "{key_path}" -N "" -C "test-backdoor-key"')
        
        if success:
            # 添加公钥到authorized_keys
            with open(f"{key_path}.pub", 'r') as f:
                pub_key = f.read().strip()
            
            with open(auth_keys_path, 'a') as f:
                f.write(f"\n{pub_key}\n")
            
            os.chmod(auth_keys_path, 0o600)
            self.log_success("测试SSH密钥后门部署成功")
            return True
        else:
            self.log_error("测试SSH密钥后门部署失败")
            return False
    
    def deploy_test_systemd_service_backdoor(self):
        """部署测试Systemd服务后门"""
        self.log_info("部署测试Systemd服务后门...")
        
        config = self.test_configs['systemd_service']
        
        # 创建执行脚本
        script_content = '''#!/bin/bash
# Test backdoor service
while true; do
    if [[ -f /tmp/.test_service_trigger ]]; then
        echo "$(date): Service triggered" >> /tmp/.test_service_log
        rm -f /tmp/.test_service_trigger
    fi
    sleep 10
done
'''
        
        with open(config['exec_script'], 'w') as f:
            f.write(script_content)
        os.chmod(config['exec_script'], 0o755)
        
        # 创建systemd服务文件
        service_content = f'''[Unit]
Description=Test Backdoor Service
After=network.target

[Service]
Type=simple
ExecStart={config['exec_script']}
Restart=always
RestartSec=10
User=root

[Install]
WantedBy=multi-user.target
'''
        
        with open(config['service_file'], 'w') as f:
            f.write(service_content)
        
        # 启用并启动服务
        success1, _, _ = self.run_command('systemctl daemon-reload')
        success2, _, _ = self.run_command(f'systemctl enable {config["service_name"]}')
        success3, _, _ = self.run_command(f'systemctl start {config["service_name"]}')
        
        if success1 and success2 and success3:
            self.log_success("测试Systemd服务后门部署成功")
            return True
        else:
            self.log_error("测试Systemd服务后门部署失败")
            return False
    
    def deploy_test_cron_backdoor(self):
        """部署测试Cron后门"""
        self.log_info("部署测试Cron后门...")
        
        config = self.test_configs['cron_job']
        
        # 创建cron脚本
        script_content = '''#!/bin/bash
# Test backdoor cron script
if [[ -f /tmp/.test_cron_trigger ]]; then
    echo "$(date): Cron triggered" >> /tmp/.test_cron_log
    rm -f /tmp/.test_cron_trigger
fi
'''
        
        with open(config['script_file'], 'w') as f:
            f.write(script_content)
        os.chmod(config['script_file'], 0o755)
        
        # 添加到crontab
        success, current_crontab, _ = self.run_command('crontab -l')
        if not success:
            current_crontab = ""
        
        new_crontab = current_crontab + "\n" + config['cron_entry'] + "\n"
        
        # 写入新的crontab
        process = subprocess.Popen(['crontab', '-'], stdin=subprocess.PIPE, text=True)
        process.communicate(input=new_crontab)
        
        if process.returncode == 0:
            self.log_success("测试Cron后门部署成功")
            return True
        else:
            self.log_error("测试Cron后门部署失败")
            return False
    
    def deploy_test_env_variable_backdoor(self):
        """部署测试环境变量后门"""
        self.log_info("部署测试环境变量后门...")
        
        config = self.test_configs['env_variable']
        
        # 创建环境变量脚本
        script_content = f'''#!/bin/bash
# Test backdoor environment script
export {config['env_var']}="test_value"

if [[ "${config['env_var']}" == "trigger_mode" ]]; then
    echo "$(date): Environment variable triggered" >> /tmp/.test_env_log
fi
'''
        
        with open(config['script_file'], 'w') as f:
            f.write(script_content)
        os.chmod(config['script_file'], 0o644)
        
        self.log_success("测试环境变量后门部署成功")
        return True
    
    def deploy_test_file_trigger_backdoor(self):
        """部署测试文件触发后门"""
        self.log_info("部署测试文件触发后门...")
        
        config = self.test_configs['file_trigger']
        
        # 创建文件监控脚本
        script_content = f'''#!/bin/bash
# Test file trigger monitor
while true; do
    if [[ -f "{config['trigger_file']}" ]]; then
        echo "$(date): File trigger detected" >> "{config['response_file']}"
        rm -f "{config['trigger_file']}"
    fi
    sleep 5
done
'''
        
        with open(config['monitor_script'], 'w') as f:
            f.write(script_content)
        os.chmod(config['monitor_script'], 0o755)
        
        # 在后台启动监控
        process = subprocess.Popen([config['monitor_script']], 
                                 stdout=subprocess.DEVNULL, 
                                 stderr=subprocess.DEVNULL)
        
        # 保存进程ID
        with open('/tmp/.test_file_monitor_pid', 'w') as f:
            f.write(str(process.pid))
        
        self.log_success("测试文件触发后门部署成功")
        return True
    
    def deploy_test_shell_alias_backdoor(self):
        """部署测试Shell别名后门"""
        self.log_info("部署测试Shell别名后门...")
        
        config = self.test_configs['shell_alias']
        bashrc_path = os.path.expanduser(config['bashrc_file'])
        
        # 备份.bashrc
        self.backup_file(bashrc_path)
        
        # 添加别名
        with open(bashrc_path, 'a') as f:
            f.write(f"\n# Test backdoor alias\n{config['alias_entry']}\n")
        
        self.log_success("测试Shell别名后门部署成功")
        return True
    
    def deploy_all_test_backdoors(self):
        """部署所有测试后门"""
        self.log_info("部署所有测试后门...")
        
        deployment_results = {}
        
        deployment_methods = {
            'ssh_key': self.deploy_test_ssh_key_backdoor,
            'systemd_service': self.deploy_test_systemd_service_backdoor,
            'cron_job': self.deploy_test_cron_backdoor,
            'env_variable': self.deploy_test_env_variable_backdoor,
            'file_trigger': self.deploy_test_file_trigger_backdoor,
            'shell_alias': self.deploy_test_shell_alias_backdoor
        }
        
        for backdoor_type, deploy_method in deployment_methods.items():
            try:
                result = deploy_method()
                deployment_results[backdoor_type] = result
                if result:
                    self.log_success(f"{backdoor_type}后门部署成功")
                else:
                    self.log_error(f"{backdoor_type}后门部署失败")
            except Exception as e:
                self.log_error(f"{backdoor_type}后门部署异常: {e}")
                deployment_results[backdoor_type] = False
        
        return deployment_results
    
    def verify_backdoor_existence(self):
        """验证后门是否存在"""
        self.log_info("验证后门存在性...")
        
        verification_results = {}
        
        # 检查SSH密钥
        ssh_key_path = os.path.expanduser(self.test_configs['ssh_key']['files'][0])
        verification_results['ssh_key'] = os.path.exists(ssh_key_path)
        
        # 检查Systemd服务
        service_name = self.test_configs['systemd_service']['service_name']
        success, _, _ = self.run_command(f'systemctl is-active {service_name}')
        verification_results['systemd_service'] = success
        
        # 检查Cron任务
        success, output, _ = self.run_command('crontab -l')
        verification_results['cron_job'] = success and 'test-backdoor-script' in output
        
        # 检查环境变量脚本
        env_script_path = self.test_configs['env_variable']['script_file']
        verification_results['env_variable'] = os.path.exists(env_script_path)
        
        # 检查文件触发监控
        monitor_script_path = self.test_configs['file_trigger']['monitor_script']
        verification_results['file_trigger'] = os.path.exists(monitor_script_path)
        
        # 检查Shell别名
        bashrc_path = os.path.expanduser(self.test_configs['shell_alias']['bashrc_file'])
        if os.path.exists(bashrc_path):
            with open(bashrc_path, 'r') as f:
                content = f.read()
            verification_results['shell_alias'] = 'test_alias_trigger' in content
        else:
            verification_results['shell_alias'] = False
        
        return verification_results
    
    def cleanup_ssh_key_backdoor(self):
        """清理SSH密钥后门"""
        self.log_info("清理SSH密钥后门...")
        
        config = self.test_configs['ssh_key']
        
        # 删除密钥文件
        for key_file in config['files']:
            key_path = os.path.expanduser(key_file)
            if os.path.exists(key_path):
                os.remove(key_path)
                self.log_info(f"已删除密钥文件: {key_path}")
        
        # 从authorized_keys中移除
        auth_keys_path = os.path.expanduser('~/.ssh/authorized_keys')
        if os.path.exists(auth_keys_path):
            with open(auth_keys_path, 'r') as f:
                lines = f.readlines()
            
            # 过滤掉测试密钥
            filtered_lines = [line for line in lines if 'test-backdoor-key' not in line]
            
            with open(auth_keys_path, 'w') as f:
                f.writelines(filtered_lines)
            
            self.log_info("已从authorized_keys中移除测试密钥")
        
        return True
    
    def cleanup_systemd_service_backdoor(self):
        """清理Systemd服务后门"""
        self.log_info("清理Systemd服务后门...")
        
        config = self.test_configs['systemd_service']
        
        # 停止并禁用服务
        self.run_command(f'systemctl stop {config["service_name"]}')
        self.run_command(f'systemctl disable {config["service_name"]}')
        
        # 删除服务文件
        if os.path.exists(config['service_file']):
            os.remove(config['service_file'])
            self.log_info(f"已删除服务文件: {config['service_file']}")
        
        # 删除执行脚本
        if os.path.exists(config['exec_script']):
            os.remove(config['exec_script'])
            self.log_info(f"已删除执行脚本: {config['exec_script']}")
        
        # 重新加载systemd
        self.run_command('systemctl daemon-reload')
        
        return True
    
    def cleanup_cron_backdoor(self):
        """清理Cron后门"""
        self.log_info("清理Cron后门...")
        
        config = self.test_configs['cron_job']
        
        # 从crontab中移除
        success, current_crontab, _ = self.run_command('crontab -l')
        if success:
            lines = current_crontab.split('\n')
            filtered_lines = [line for line in lines if 'test-backdoor-script' not in line]
            new_crontab = '\n'.join(filtered_lines)
            
            # 写入新的crontab
            process = subprocess.Popen(['crontab', '-'], stdin=subprocess.PIPE, text=True)
            process.communicate(input=new_crontab)
        
        # 删除脚本文件
        if os.path.exists(config['script_file']):
            os.remove(config['script_file'])
            self.log_info(f"已删除脚本文件: {config['script_file']}")
        
        return True
    
    def cleanup_env_variable_backdoor(self):
        """清理环境变量后门"""
        self.log_info("清理环境变量后门...")
        
        config = self.test_configs['env_variable']
        
        # 删除环境变量脚本
        if os.path.exists(config['script_file']):
            os.remove(config['script_file'])
            self.log_info(f"已删除环境变量脚本: {config['script_file']}")
        
        return True
    
    def cleanup_file_trigger_backdoor(self):
        """清理文件触发后门"""
        self.log_info("清理文件触发后门...")
        
        config = self.test_configs['file_trigger']
        
        # 停止监控进程
        pid_file = '/tmp/.test_file_monitor_pid'
        if os.path.exists(pid_file):
            with open(pid_file, 'r') as f:
                pid = f.read().strip()
            
            try:
                self.run_command(f'kill {pid}')
                self.log_info(f"已停止监控进程: {pid}")
            except:
                pass
            
            os.remove(pid_file)
        
        # 删除监控脚本
        if os.path.exists(config['monitor_script']):
            os.remove(config['monitor_script'])
            self.log_info(f"已删除监控脚本: {config['monitor_script']}")
        
        # 清理触发和响应文件
        for file_path in [config['trigger_file'], config['response_file']]:
            if os.path.exists(file_path):
                os.remove(file_path)
                self.log_info(f"已删除文件: {file_path}")
        
        return True
    
    def cleanup_shell_alias_backdoor(self):
        """清理Shell别名后门"""
        self.log_info("清理Shell别名后门...")
        
        config = self.test_configs['shell_alias']
        bashrc_path = os.path.expanduser(config['bashrc_file'])
        
        if os.path.exists(bashrc_path):
            with open(bashrc_path, 'r') as f:
                lines = f.readlines()
            
            # 过滤掉测试别名
            filtered_lines = []
            skip_next = False
            for line in lines:
                if 'Test backdoor alias' in line:
                    skip_next = True
                    continue
                if skip_next and 'test_alias_trigger' in line:
                    skip_next = False
                    continue
                if not skip_next:
                    filtered_lines.append(line)
            
            with open(bashrc_path, 'w') as f:
                f.writelines(filtered_lines)
            
            self.log_info("已从.bashrc中移除测试别名")
        
        return True
    
    def cleanup_all_test_backdoors(self):
        """清理所有测试后门"""
        self.log_info("清理所有测试后门...")
        
        cleanup_results = {}
        
        cleanup_methods = {
            'ssh_key': self.cleanup_ssh_key_backdoor,
            'systemd_service': self.cleanup_systemd_service_backdoor,
            'cron_job': self.cleanup_cron_backdoor,
            'env_variable': self.cleanup_env_variable_backdoor,
            'file_trigger': self.cleanup_file_trigger_backdoor,
            'shell_alias': self.cleanup_shell_alias_backdoor
        }
        
        for backdoor_type, cleanup_method in cleanup_methods.items():
            try:
                result = cleanup_method()
                cleanup_results[backdoor_type] = result
                if result:
                    self.log_success(f"{backdoor_type}后门清理成功")
                else:
                    self.log_error(f"{backdoor_type}后门清理失败")
            except Exception as e:
                self.log_error(f"{backdoor_type}后门清理异常: {e}")
                cleanup_results[backdoor_type] = False
        
        return cleanup_results
    
    def verify_cleanup_completeness(self):
        """验证清理完整性"""
        self.log_info("验证清理完整性...")
        
        verification_results = self.verify_backdoor_existence()
        
        # 检查是否所有后门都已清理
        all_cleaned = all(not exists for exists in verification_results.values())
        
        if all_cleaned:
            self.log_success("所有测试后门已完全清理")
        else:
            self.log_warning("部分后门可能未完全清理")
            for backdoor_type, exists in verification_results.items():
                if exists:
                    self.log_warning(f"{backdoor_type}后门仍然存在")
        
        return verification_results
    
    def test_recovery_functionality(self):
        """测试恢复功能"""
        self.log_info("测试恢复功能...")
        
        recovery_results = {}
        
        # 测试从备份恢复文件
        backup_files = os.listdir(self.backup_dir)
        for backup_file in backup_files:
            backup_path = os.path.join(self.backup_dir, backup_file)
            
            if backup_file == 'authorized_keys':
                original_path = '~/.ssh/authorized_keys'
            elif backup_file == '.bashrc':
                original_path = '~/.bashrc'
            else:
                continue
            
            try:
                success = self.restore_file(original_path, backup_path)
                recovery_results[backup_file] = success
                if success:
                    self.log_success(f"文件恢复成功: {backup_file}")
                else:
                    self.log_error(f"文件恢复失败: {backup_file}")
            except Exception as e:
                self.log_error(f"文件恢复异常: {backup_file} - {e}")
                recovery_results[backup_file] = False
        
        return recovery_results
    
    def run_full_cleanup_test(self):
        """运行完整的清理测试"""
        self.log_info(f"开始权限维持清理验证测试 (会话ID: {self.session_id})")
        
        try:
            # 1. 部署测试后门
            self.log_info("阶段1: 部署测试后门")
            deployment_results = self.deploy_all_test_backdoors()
            
            # 2. 验证后门存在
            self.log_info("阶段2: 验证后门存在性")
            existence_before = self.verify_backdoor_existence()
            
            # 3. 清理后门
            self.log_info("阶段3: 清理测试后门")
            cleanup_results = self.cleanup_all_test_backdoors()
            
            # 4. 验证清理完整性
            self.log_info("阶段4: 验证清理完整性")
            existence_after = self.verify_cleanup_completeness()
            
            # 5. 测试恢复功能
            self.log_info("阶段5: 测试恢复功能")
            recovery_results = self.test_recovery_functionality()
            
            # 汇总结果
            self.results['cleanup_tests'] = {
                'deployment': deployment_results,
                'existence_before': existence_before,
                'cleanup': cleanup_results,
                'existence_after': existence_after
            }
            
            self.results['recovery_tests'] = recovery_results
            
            # 计算总体状态
            cleanup_success_rate = sum(cleanup_results.values()) / len(cleanup_results)
            recovery_success_rate = sum(recovery_results.values()) / len(recovery_results) if recovery_results else 1.0
            
            if cleanup_success_rate >= 0.9 and recovery_success_rate >= 0.8:
                self.results['overall_status'] = 'excellent'
            elif cleanup_success_rate >= 0.7 and recovery_success_rate >= 0.6:
                self.results['overall_status'] = 'good'
            elif cleanup_success_rate >= 0.5:
                self.results['overall_status'] = 'fair'
            else:
                self.results['overall_status'] = 'poor'
            
            self.log_info(f"清理验证测试完成，总体状态: {self.results['overall_status']}")
            
        except Exception as e:
            self.log_error(f"测试过程中发生错误: {e}")
            self.results['overall_status'] = 'error'
        
        finally:
            # 清理临时文件
            self.cleanup_temp_files()
        
        return self.results
    
    def cleanup_temp_files(self):
        """清理临时文件"""
        temp_files = [
            '/tmp/.test_service_trigger',
            '/tmp/.test_service_log',
            '/tmp/.test_cron_trigger',
            '/tmp/.test_cron_log',
            '/tmp/.test_env_log'
        ]
        
        for temp_file in temp_files:
            if os.path.exists(temp_file):
                os.remove(temp_file)
    
    def save_results(self, output_dir="reports"):
        """保存测试结果"""
        os.makedirs(output_dir, exist_ok=True)
        
        # 保存JSON报告
        json_file = os.path.join(output_dir, f"cleanup_verification_{self.session_id}.json")
        with open(json_file, 'w', encoding='utf-8') as f:
            json.dump(self.results, f, indent=2, ensure_ascii=False)
        
        # 保存Markdown报告
        md_file = os.path.join(output_dir, f"cleanup_verification_{self.session_id}.md")
        self.generate_markdown_report(md_file)
        
        self.log_info(f"测试结果已保存: {json_file}, {md_file}")
    
    def generate_markdown_report(self, output_file):
        """生成Markdown格式的报告"""
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(f"# Linux权限维持清理验证报告\n\n")
            f.write(f"**会话ID**: {self.results['session_id']}\n")
            f.write(f"**测试时间**: {self.results['timestamp']}\n")
            f.write(f"**总体状态**: {self.results['overall_status']}\n\n")
            
            # 状态说明
            status_desc = {
                'excellent': '🟢 优秀 - 清理和恢复功能完善',
                'good': '🟡 良好 - 清理和恢复功能基本正常',
                'fair': '🟠 一般 - 清理功能部分有效',
                'poor': '🔴 较差 - 清理功能存在问题',
                'error': '❌ 错误 - 测试过程中发生异常'
            }
            
            f.write(f"**状态说明**: {status_desc.get(self.results['overall_status'], '未知')}\n\n")
            
            # 清理测试结果
            f.write("## 清理测试结果\n\n")
            
            if 'cleanup_tests' in self.results:
                cleanup_tests = self.results['cleanup_tests']
                
                f.write("### 部署测试\n\n")
                for backdoor_type, success in cleanup_tests.get('deployment', {}).items():
                    status = "✅ 成功" if success else "❌ 失败"
                    f.write(f"- **{backdoor_type}**: {status}\n")
                
                f.write("\n### 清理测试\n\n")
                for backdoor_type, success in cleanup_tests.get('cleanup', {}).items():
                    status = "✅ 成功" if success else "❌ 失败"
                    f.write(f"- **{backdoor_type}**: {status}\n")
                
                f.write("\n### 清理验证\n\n")
                for backdoor_type, exists in cleanup_tests.get('existence_after', {}).items():
                    status = "✅ 已清理" if not exists else "❌ 仍存在"
                    f.write(f"- **{backdoor_type}**: {status}\n")
            
            # 恢复测试结果
            f.write("\n## 恢复测试结果\n\n")
            
            if 'recovery_tests' in self.results and self.results['recovery_tests']:
                for file_name, success in self.results['recovery_tests'].items():
                    status = "✅ 成功" if success else "❌ 失败"
                    f.write(f"- **{file_name}**: {status}\n")
            else:
                f.write("无需要恢复的文件\n")
            
            # 测试统计
            f.write("\n## 测试统计\n\n")
            
            if 'cleanup_tests' in self.results:
                cleanup_tests = self.results['cleanup_tests']
                
                # 清理成功率
                cleanup_results = cleanup_tests.get('cleanup', {})
                if cleanup_results:
                    success_count = sum(cleanup_results.values())
                    total_count = len(cleanup_results)
                    success_rate = (success_count / total_count) * 100
                    f.write(f"- **清理成功率**: {success_rate:.1f}% ({success_count}/{total_count})\n")
                
                # 恢复成功率
                recovery_results = self.results.get('recovery_tests', {})
                if recovery_results:
                    success_count = sum(recovery_results.values())
                    total_count = len(recovery_results)
                    success_rate = (success_count / total_count) * 100
                    f.write(f"- **恢复成功率**: {success_rate:.1f}% ({success_count}/{total_count})\n")
            
            # 测试项目
            f.write("\n## 测试项目\n\n")
            test_items = [
                "SSH密钥后门清理",
                "Systemd服务后门清理",
                "Cron定时任务后门清理",
                "环境变量后门清理",
                "文件触发后门清理",
                "Shell别名后门清理",
                "文件恢复功能",
                "清理完整性验证"
            ]
            
            for item in test_items:
                f.write(f"- {item}\n")
            
            f.write(f"\n---\n*报告生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*\n")

def main():
    """主函数"""
    print("Linux权限维持清理验证器")
    print("=" * 50)
    
    if len(sys.argv) > 1 and sys.argv[1] == '--help':
        print("用法: python3 persistence_cleanup_verifier.py [选项]")
        print("选项:")
        print("  --help    显示帮助信息")
        print("  --output  指定输出目录 (默认: reports)")
        return
    
    # 检查权限
    if os.geteuid() != 0:
        print("[ERROR] 此脚本需要root权限运行")
        print("请使用: sudo python3 persistence_cleanup_verifier.py")
        sys.exit(1)
    
    # 解析命令行参数
    output_dir = "reports"
    if len(sys.argv) > 2 and sys.argv[1] == '--output':
        output_dir = sys.argv[2]
    
    # 创建验证器实例
    verifier = PersistenceCleanupVerifier()
    
    try:
        # 运行测试
        results = verifier.run_full_cleanup_test()
        
        # 保存结果
        verifier.save_results(output_dir)
        
        # 显示摘要
        print("\n" + "=" * 50)
        print("测试摘要:")
        print(f"总体状态: {results['overall_status']}")
        
        if 'cleanup_tests' in results:
            cleanup_tests = results['cleanup_tests']
            
            # 清理成功率
            cleanup_results = cleanup_tests.get('cleanup', {})
            if cleanup_results:
                success_count = sum(cleanup_results.values())
                total_count = len(cleanup_results)
                print(f"清理成功率: {(success_count/total_count)*100:.1f}% ({success_count}/{total_count})")
            
            # 恢复成功率
            recovery_results = results.get('recovery_tests', {})
            if recovery_results:
                success_count = sum(recovery_results.values())
                total_count = len(recovery_results)
                print(f"恢复成功率: {(success_count/total_count)*100:.1f}% ({success_count}/{total_count})")
        
    except KeyboardInterrupt:
        print("\n测试被用户中断")
    except Exception as e:
        print(f"测试过程中发生错误: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()